package top.zpengblog.db2document.jdbc;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.lang3.StringUtils;
import top.zpengblog.db2document.constant.SysConstant;
import top.zpengblog.db2document.model.ConnectionInfo;

import javax.sql.DataSource;
import javax.swing.*;
import java.sql.Connection;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 数据库连接管理.
 *
 * @author ZhiPeng.Lin (codingjava@qq.com)
 * @version 1.0.0
 * @date 2022/1/27 23:48
 */
public class ConnectionManager {

    // datasource 容器
    private static final ConcurrentHashMap<String, DataSource> dataSourceMap = new ConcurrentHashMap<>(8);

    private static DruidDataSource getDruidDataSource(ConnectionInfo info) {
        // 校验连接信息
        checkInfo(info);

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setBreakAfterAcquireFailure(true);
        //设置获取连接出错时的自动重连次数
        //druidDataSource.setConnectionErrorRetryAttempts(3);
        //设置获取连接出错时是否马上返回错误，true为马上返回
        druidDataSource.setFailFast(true);
        String url = String.format(SysConstant.MYSQL_URL_TEMPLATE, info.getAddress(), info.getPort(), info.getDatabase());
        druidDataSource.setDriverClassName(SysConstant.MYSQL_DRIVER_CLASS);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(info.getUserName());
        druidDataSource.setPassword(info.getUserPassword());
        return druidDataSource;
    }

    private static void checkInfo(ConnectionInfo info) {
        if (StringUtils.isAnyBlank(info.getAddress(), info.getDatabase(),
                info.getPort(), info.getUserName())) {
            throw new RuntimeException("连接信息填写错误 !");
        }
    }

    public static Connection getConnectionByCache(ConnectionInfo connectionInfo) {
        String key = connectionInfo.toString();
        try{
            DataSource ds = dataSourceMap.computeIfAbsent(key, info -> getDruidDataSource(connectionInfo));
            return ds.getConnection();
        } catch (Exception e){
            //连接出错， 应该清除缓存
            dataSourceMap.remove(key);
            JOptionPane.showMessageDialog(null, "获取连接失败！msg = " + e.getMessage(), "结果", JOptionPane.ERROR_MESSAGE);
            return null;
        }
    }
}
